import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, KeyboardAvoidingView, Platform, ScrollView, TouchableOpacity, Image, TextInput } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RemarkCpt } from './_components/form/RemarkCpt';
import { GoodsModuleCpt } from './_components/form/GoodsModuleCpt';
import OfferAPIService from './_common/OfferAPIService';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ResourceBaseInfoCard } from '../_components/resourceBaseInfoCard';//../_components/resourceBaseInfoCard
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import OfferCreateMethods from './OfferCreateMethods';
import { DatePicker } from 'react-native-pickers';
import { RadoiCpt } from './_components/form/RadoiCpt';
import { offerStyle } from './_components/form/offerStyle';
import Utils from '../../../utils/utils';
import { AttachmentCpt } from './_components/form/AttachmentCpt';
import { RefuseModal } from '../../../component/ModalVerifylComponent.js';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;



export class OneRoundPage extends Component {
	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: `新增${params.salesType == 'S' ? '销售' : '采购'}资源`,
			headerTintColor: style.color.white,//
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color="#fff" />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: style.head.headerTitleStyle
		}
	};

	constructor(props) {
		super(props);
		let { notFirst } = this.props.navigation.state.params || {};
		this.state = {
			pageState: 'loading',
			refuseModalVisible: false
		}
		//表单提交参数
		this.sendData = OfferCreateMethods.defualtParams(props);
		this.notFirst = notFirst;
	}

	componentWillMount() {
		this._init();
	}

	componentWillUnmount() {
		this.sendData = null;
		this.setState = () => {
			return
		}
	}

	_init = async () => {
		await this._getDictList();
		await this._editor();
		this.setState({
			pageState: 'data'
		})
	}

	//编辑
	_editor = async () => {
		let { bidPackageApplyId } = this.props.navigation.state.params || {};
		if (!bidPackageApplyId) return;
		let editorRes = await OfferAPIService.offerEdit({ bidPackageApplyId });
		console.log('editorRes-编辑', editorRes)
		if (editorRes && editorRes.bidPackageApplyId) {
			this.sendData.packageApplyInfo = this._modifyData(editorRes);
			this.setState({
				fileIdArry: editorRes.fileIdArry
				// fileIdArry: ['21030414520490432116635129', '21030414521970372390151129']
			})
		}
	}

	//修改数据
	_modifyData = (editorRes) => {
		let { resourceApplyList, priceType } = editorRes || {};
		if (priceType) { // 处理价格类型(主项下放到子项)
			resourceApplyList && resourceApplyList.map((item) => {
				item.priceType = priceType;
				item.symbol = item.udPrice >= 0 ? true : false; //升贴水
				//item.udPrice = Math.abs(item.udPrice);
				return item;
			})
		}
		return editorRes;
	}


	//获取数据库字典
	_getDictList = async () => {
		this.priceTypeData = await OfferCreateMethods.getDict('EC_PRICE_TYPE'); //价格类型 一口价 暂定价
		this.timeTypeData = await OfferCreateMethods.getDict('CRM_EFFECTIVE_TIME_TYPE');//资源有效时段
	}


	//商品回调数据
	_goodsCallback = (data) => {
		this.sendData.packageApplyInfo.resourceApplyList = OfferCreateMethods.goodsCallback(data);
		console.log('this.sendData', this.sendData)
	}

	//计划上架时间 弹框
	_openTimeFn = () => {
		this.DatePicker.show();
	}

	//回调
	_baseCallBack = (data) => {
		let { packageApplyInfo } = this.sendData || {};
		this.sendData.packageApplyInfo = Object.assign({}, packageApplyInfo, data);
		for (var key in data) {
			if (key === 'bizModel') { // 如果是报盘 刷新页面
				if (data[key] === "Z" || data[key] === "DD") { // 招标
					if (!this.sendData.packageApplyInfo.isFullPricesRequired) this.sendData.packageApplyInfo.isFullPricesRequired = 'Y';  //是否所有价格必填
					if (!this.sendData.packageApplyInfo.isFullPackageFix) this.sendData.packageApplyInfo.isFullPackageFix = 'Y';  //是否整包提报
				}
				if (data[key] === "P") {
					if (!this.sendData.packageApplyInfo.isSubmitPrepay) this.sendData.packageApplyInfo.isSubmitPrepay = 'N';  //是否缴纳保证金
				}
				this.sendData.packageApplyInfo = initDate.bizModel(this.sendData.packageApplyInfo, data[key]); //处理数据
				this.setState({ ls: true });
			}
		}
		console.log('基本-回调', this.sendData)
	}
	showPackageName = async () => {
		this.sendData.load = true;
		if (OfferCreateMethods.validation(this.sendData)) {
			this.sendData.load = false;
			return this.sendData;
		}
		if (this.sendData.bizType === 'EDIT') {
			this.sendData.load = false;
			this.setState({
				refuseModalVisible: true
			})
		}
		else {
			let res = await HTTP.POST(API_GENERATE(API.PACKAGE_APPLY_NAME), this.sendData);
			this.sendData.load = false;
			if (res) {
				this.sendData.packageApplyInfo.bidPackageName = res
				this.setState({
					refuseModalVisible: true
				})
			}
		}
	}

	render() {
		let { pageState, fileIdArry } = this.state;
		let { packageApplyInfo } = this.sendData || {};
		let { bizModel, resourceApplyList, tranDesc, salesType, upTime, applyRemark, effectiveTimeType, effectiveHour, effectiveMinute } = packageApplyInfo || {};
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				{
					pageState === 'data' ? (
						<View style={{ flex: 1, position: 'relative' }}>
							<ScrollView showsVerticalScrollIndicator={false} keyboardShouldPersistTaps={'handled'}>
								<View style={styles.ScrollViewInner}>
									<View style={styles.box}>
										<ResourceBaseInfoCard
											stylesData={{ padding: 0 }}
											data={packageApplyInfo}
											titleAction={false}
											copyPress={() => { navigationSeevice.navigate('OfferCreatePage', { salesType, bidPackageApplyId: resDetail.bidPackageApplyId, isCopy: true }); }} />
										<GoodsModuleCpt notAdd={true} dictionaryData={this.priceTypeData} data={{ bizModel, salesType, editeData: resourceApplyList }} goodsCallback={this._goodsCallback} />
										<RadoiCpt data={{
											id: 'effectiveTimeType',
											title: '资源有效时段',
											listData: this.timeTypeData,
											selectKey: effectiveTimeType,
											layStyle: offerStyle.layStyle,
											other: { type: 'time-hours', effectiveHour, effectiveMinute, otherKey: 'O' }
										}}
											callBack={this._baseCallBack}
										/>
										<RadoiCpt data={{
											id: 'upTime',
											title: '计划上架时间',
											listData: [],
											layStyle: offerStyle.layStyle,
											selectKey: upTime,
											required: true
										}}
											callBack={this._openTimeFn}
										/>
										<AttachmentCpt data={{
											title: '附件',
											fileIdArry: fileIdArry
										}}
											getItemInfo={(val) => {
												this.sendData.packageApplyInfo.resourceBidPackageFileVOS = val
											}}
											propsData={this.props}
										/>
										<RemarkCpt data={{
											id: 'tranDesc',
											title: '特别说明',
											selectKey: tranDesc,
										}}
											callBack={this._baseCallBack}
										/>
										{/* <RemarkCpt data={{
											id: 'applyRemark',
											title: '送审备注',
											selectKey: applyRemark,
										}}
											callBack={this._baseCallBack}
										/> */}
										<View >
											<Text >{'送审备注' || '-'}</Text>
											<TextInput underlineColorAndroid='transparent' style={[offerStyle.fontBold, styles.textArea]} defaultValue={Utils.numberToString(applyRemark)} multiline={true} numberOfLines={6} maxLength={2000} placeholder='限定2000字' onChangeText={(value) => {
												//this._baseCallBack({ applyRemark: value })
												this.sendData.packageApplyInfo.applyRemark = value;
											}} />
										</View>
									</View>
								</View >
							</ScrollView>
							<View style={styles.btnBoxBig}>
								<View style={styles.btnBox}>
									<TouchableOpacity style={styles.BtnBg} onPress={() => {
										this.sendData.bizType = this.notFirst ? 'EDIT' : 'READD';
										this.sendData.saveType = "SUBMIT";
										this.showPackageName()
										// OfferCreateMethods.submit(this.sendData);
									}}>
										<Text style={styles.BtnText}>{this.notFirst ? '提交申请' : '再来一轮'}</Text>
									</TouchableOpacity>
								</View>
							</View>

						</View>
					) : (<View style={styles.statusStyle}><PageStatusIndex status={pageState} /></View>)
				}
				<DatePicker
					unit={['年', '月', '日']}
					startYear={2000}
					endYear={2100}
					onPickerConfirm={(timeArr) => {
						let timeStr = '';
						timeArr && timeArr.forEach((item, index) => {
							item = item.substring(0, item.length - 1);
							if (index < 2) {
								timeStr += item + '-';
							}
							else if (index == 2) {
								timeStr += item
							} else if (index == 3) {
								timeStr += " " + item
							} else if (index == 4) {
								timeStr += ":" + item;
							}
							console.log('timeStr999', timeStr)
						})
						this.sendData.packageApplyInfo.upTime = timeStr;
						this.setState({ ls: true })
						console.log('	this.sendData.packageApplyInfo', this.sendData.packageApplyInfo)
					}}
					onPickerCancel={() => {
						alert('cancel')
					}}
					ref={ref => this.DatePicker = ref}
				/>
				<RefuseModal
					titleText={'当前资源包名称'}
					placeholderText={'请输入资源包名称'}
					propsDefaultValue={this.sendData.packageApplyInfo.bidPackageName}
					visible={this.state.refuseModalVisible}
					btnPress={(bidPackageName) => {
						this.sendData.packageApplyInfo.bidPackageName = bidPackageName;
						OfferCreateMethods.submit(this.sendData)
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						})
					}}
				/>
			</KeyboardAvoidingView>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#E8ECF5',
	},
	ScrollViewInner: {
		marginBottom: 80 * scale
	},
	statusStyle: {
		flex: 1,
		position: 'absolute',
		height: '100%',
		width: Dimensions.get('window').width,
		top: 0,
		left: 0,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center'
	},
	box: {
		marginHorizontal: 20 * scale,
		paddingVertical: 10 * scale
	},
	btnBoxBig: {
		position: 'absolute',
		bottom: 0,
		left: 0,
		width: '100%',
		height: 80 * scale,
		backgroundColor: '#E8ECF5',
	},
	btnBox: {
		flexDirection: 'row',
		justifyContent: 'center',
		marginVertical: 20 * scale,
	},
	BtnBg: {
		backgroundColor: style.color.themeColor,
		paddingHorizontal: 25 * scale,
		//paddingVertical: 10 * scale,
		height: 32 * scale,
		borderRadius: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	BtnText: {
		fontSize: 13 * scale,
		color: style.color.white
	},
	BtnBgR: {
		marginLeft: 30 * scale
	},
	textArea: {
		height: 64 * scale,
		backgroundColor: '#fff',
		marginTop: 10 * scale,
		borderRadius: 8 * scale,
		paddingHorizontal: 15 * scale,
		paddingVertical: 35 * scale,
		paddingVertical: 0,
		borderWidth: 0,
		marginBottom: 20 * scale
	}
})